from celery import shared_task
from apps.hosttools.models import City,Host, HostStatistics
from django.utils import timezone
from django.db.models import Count
import subprocess,datetime



@shared_task
def check_host_status():
    hosts = Host.objects.all()
    for host in hosts:
        response = ping_host(host.ip_address)
        host.is_online = response
        host.updated_at = datetime.now()  # 更新为当前时间
        host.save()  # 保存到数据库
    static_host_count()
    
def ping_host(ip):
    """通过系统命令 ping 主机并返回是否在线"""
    try:
        # 对于 Linux/Unix 系统
        response = subprocess.run(
            ["ping", "-c", "1", str(ip)],  # 对于 Windows 系统是 ["ping", "-n", "1", str(ip)]
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        return response.returncode == 0  # 如果返回码为 0，说明主机在线
    except Exception:
        return False  # 如果发生错误，返回主机不在线



def static_host_count():
    today = timezone.now().date()
    cities = City.objects.all()

    for city in cities:
        data_centers = city.data_centers.all()

        for data_center in data_centers:
            host_count = Host.objects.filter(data_center=data_center).count()

            # 存储统计数据到数据库
            HostStatistics.objects.update_or_create(
                city=city,
                data_center=data_center,
                date=today,
                defaults={'host_count': host_count}
            )
